package com.tgy.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * @author tianguiyin
 * @version 1.0
 * @date 2022/7/14 14:40
 */
public class AddressUtils {

    // 百度定位ak（更改为自己的）
    private static String ak = "";

    /**
     * 根据IP获取所属地
     * @param ip    外网IP地址
     */
    public static String getAddress(String ip) throws IOException {
        // 这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
        JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ip="+ip+"&ak="+ak);

        /*JSONObject obj = (JSONObject) ((JSONObject) json.get("content")).get("address_detail");
        String province = obj.getString("province");
        System.out.println(province);*/

        JSONObject obj2 = (JSONObject) json.get("content");
        return obj2.getString("address");
    }

    /**
     * 创建链接
     *
     * @param url   地址
     */
    private static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            return JSONObject.parseObject(jsonText);
        } finally {
            is.close();
        }
    }


    /**
     * 读取
     * @param rd    Reader
     */
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

}
